<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图 -->
    <el-card border stripe>
      <el-row>
        <el-col>
          <!-- 添加角色按钮去 -->
          <el-button type="primary" @click="addRolesDialogVisible = true">添加角色</el-button>
        </el-col>
      </el-row>
      <!--  -->
      <el-table :data="rolesList" border stripe>
        <!-- 展开列 -->
        <el-table-column type="expand">
          <template slot-scope="scope">
            <el-row v-for="(item1, i) in scope.row.children" :key="item1.id" :class="['dbbottom', i == 0 ? 'bdtop' : '', 'vcenter']">
              <!-- 渲染一级权限 -->
              <el-col :span="5">
                <el-tag closable @close="removeRightById(scope.row, item1.id)">
                  {{ item1.authName }}
                </el-tag>
                <i class="el-icon-caret-right"></i>
              </el-col>
              <!-- 渲染二级三级权限 -->
              <el-col :span="19">
                <!-- 通过for循环嵌套渲染二级权限 -->
                <el-row v-for="(item2, i) in item1.children" :key="item2.id" :class="[i == 0 ? '' : 'bdtop', 'vcenter']">
                  <el-col :span="6">
                    <el-tag type="success" closable @close="removeRightById(scope.row, item2.id)">{{ item2.authName }}</el-tag>
                    <i class="el-icon-caret-right"></i>
                  </el-col>

                  <el-col :span="18">
                    <el-tag type="warning" v-for="item3 in item2.children" :key="item3.id" closable @close="removeRightById(scope.row, item3.id)">{{ item3.authName }}</el-tag>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
            <!-- <pre>{{ scope.row }}</pre> -->
          </template>
        </el-table-column>
        <!-- 索引列 -->
        <el-table-column type="index"></el-table-column>
        <el-table-column label="角色名称" prop="roleName"></el-table-column>
        <el-table-column label="角色描述" prop="roleDesc"></el-table-column>
        <el-table-column label="操作" width="300px">
          <template slot-scope="scope">
            <el-button type="primary" size="mini" icon="el-icon-edit" @click="editRight(scope.row)">编辑</el-button>
            <el-button type="danger" size="mini" icon="el-icon-delete" @click="deleteRight(scope.row)">删除</el-button>
            <el-button type="warning" size="mini" icon="el-icon-setting" @click="showSetRightDialog(scope.row)">分配权限</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <!-- 分配权限的对话框 -->
    <el-dialog title="分配权限" :visible.sync="setRightdialogVisible" width="50%" @close="setRightDialongClose">
      <!-- 树形控件 -->
      <el-tree :data="rightList" :props="treetProps" show-checkbox node-key="id" default-expand-all :default-checked-keys="defKeys" ref="treeRef"></el-tree>
      <!--  -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="setRightdialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="allorRights">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 添加角色的对话框 -->
    <el-dialog title="添加用户" :visible.sync="addRolesDialogVisible" width="50%">
      <!-- 内容主题区域 -->
      <el-form label-width="80px">
        <el-form-item label="角色名称">
          <el-input v-model="roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述">
          <el-input v-model="roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <!-- 底部区域 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">
          取 消
        </el-button>
        <el-button type="primary" @click="addRigth">
          确 定
        </el-button>
      </span>
    </el-dialog>
    <!-- 编辑角色对话框 -->
    <el-dialog title="添加用户" :visible.sync="editRolesDialogVisible" width="50%">
      <!-- 内容主题区域 -->
      <el-form label-width="80px">
        <el-form-item label="角色名称">
          <el-input v-model="roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述">
          <el-input v-model="roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <!-- 底部区域 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="editRolesDialogVisible = false">
          取 消
        </el-button>
        <el-button type="primary" @click="commiteRigth">
          确 定
        </el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
export default {
  data() {
    return {
      // 所有角色列表数据
      rolesList: [],
      // 控制分配权限的关闭和打开
      setRightdialogVisible: false,
      // 所有权限的数据
      rightList: [],
      // 数形控件的属性绑定对象
      treetProps: {
        children: "children",
        label: "authName"
      },
      // 默认选中的节点id值数组
      defKeys: [105, 116],
      // 当前点击的角色的id
      roleId: "",
      // 添加角色的控制
      addRolesDialogVisible: false,
      // 角色名称
      roleName: "",
      // 角色描述
      roleDesc: "",
      // 控制编辑的对话框
      editRolesDialogVisible: false,
      // 编辑的当前角色的id
      scopeId: ""
    }
  },
  created() {
    this.getRoles()
  },
  methods: {
    async getRoles() {
      const { data: res } = await this.$http.get("roles")
      if (res.meta.status !== 200) return this.$message.error("获取列表失败")
      this.rolesList = res.data
      console.log(res)
    },
    // 根据id删第三级分类
    async removeRightById(role, rightId) {
      // 弹框提示用户是否删除
      const result = await this.$confirm("此操作将永久删除该文件, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).catch(error => error)
      console.log(result)
      if (result !== "confirm") return this.$message.info("取消了删除")
      const { data: res } = await this.$http.delete(`roles/${role.id}/rights/${rightId}`)
      console.log(res)
      if (res.meta.status !== 200) {
        return this.$$message.error("删除权限失败！")
      }
      this.$message.success(res.meta.msg)
      // this.getRoles()不建议，会导致页面的完整渲染
      // 这个取消权限的接口返回值就是我们操作过后的新内容
      // 只需要重新赋值给，这样就不会导致页面的重绘，和把当前的展开内容收起来
      role.children = res.data
    },
    // 展示分配权限的对话框
    async showSetRightDialog(role) {
      // 获取所有权限的数据
      const { data: res } = await this.$http.get("rights/tree")
      if (res.meta.status !== 200) {
        return this.$message.error("获取列表失败")
      }
      this.rightList = res.data
      console.log(res)
      // 递归获取三级节点的id
      this.getLeafKeys(role, this.defKeys)
      this.setRightdialogVisible = true
      // 保存当前角色id 后续的接口需要用到
      this.roleId = role.id
    },
    // 通过递归的形式， 获取所有三级权限的id保存到 defKeys 中
    getLeafKeys(node, arr) {
      // 如果当前node节点不包含children 就代表是三级节点
      if (!node.children) {
        return arr.push(node.id)
      }
      node.children.forEach(item => {
        this.getLeafKeys(item, arr)
      })
    },
    // 监听权限管理对话框关闭事件
    setRightDialongClose() {
      this.defKeys = []
      // 每一次我们关闭的时候都需要清空，不然不清空，在点击下一个人的权限管理的时候，上一次的人的权限管理的内容也
      // 会被显示出来，我们只需要显示一个人的 就是当前的人的权限
    },
    // 点击为角色分配权限的确认按钮
    async allorRights() {
      const keys = [
        ...this.$refs.treeRef.getCheckedKeys(), //ui提供的方法获取全选的状态的id
        ...this.$refs.treeRef.getHalfCheckedKeys() //ui提供的方法获取半选的状态的id
      ]
      const obj = keys.join(",")
      const { data: res } = await this.$http.post(`roles/${this.roleId}/rights`, { rids: obj })
      if (res.meta.status !== 200) return this.$message.error("分配角色失败")
      this.$message.success("分配角色成功")
      this.getRoles()
      this.setRightdialogVisible = false
    },
    // 添加角色
    async addRigth() {
      const { data: res } = await this.$http.post("roles", {
        roleName: this.roleName,
        roleDesc: this.roleDesc
      })
      console.log(res)
      if (res.meta.status !== 201) return this.$message.error("添加角色失败")
      this.$message.success("添加角色成功")
      this.addRolesDialogVisible = false
      this.getRoles()
    },
    //
    // 编辑角色
    editRight(scope) {
      console.log(scope.id)
      this.scopeId = scope.id
      this.roleName = scope.roleName
      this.roleDesc = scope.roleDesc
      this.editRolesDialogVisible = true
    },
    async commiteRigth() {
      const { data: res } = await this.$http.put("roles/" + this.scopeId, {
        roleName: this.roleName,
        roleDesc: this.roleDesc
      })
      console.log(res)
      if (res.meta.status !== 200) return this.$message.error("修改失败")
      this.$message.success("修改成功")
      this.editRolesDialogVisible = false
      this.getRoles()
    },
    // 删除角色
    async deleteRight(scope) {
      const result = await this.$confirm("此操作将永久删除该文件, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).catch(error => error)
      if (result !== "confirm") return this.$message.info("取消了删除")
      const { data: res } = await this.$http.delete("roles/" + scope.id)
      console.log(res)
      if (res.meta.status !== 200) return this.$message.error("删除失败")
      this.$message.success("删除成功")
      this.getRoles()
    }
  }
}
</script>
<style scoped>
.el-tag {
  margin: 7px;
}
.bdtop {
  border-top: 1px solid #eee;
}
.dbbottom {
  border-bottom: 1px solid #eee;
}
.vcenter {
  display: flex;
  align-items: center;
}
</style>
